function [alphat,varargout]= filterSmootherCK_trunc(data,TT,n,m,k,q,alpha_0,P_0,state_space,varargin)
twist = 0;
whx = 0;
% State Space system as in Harvey (1989)
% measurement equation: y(t) = d + Z alpha(t) + epsilon(t)
% transition equation: alpha(t+1) = c + T alpha(t) + R eta(t)

alpha_s=zeros(m,TT);

alpha_u=zeros(m,TT+1);
P_u=zeros(m,m,TT+1);
alpha_f=zeros(m,TT);
P_f=zeros(m,m,TT);

%P_transform = @(Pcov) 0.5*(Pcov + Pcov');

alpha_u(:,1)=alpha_0;
P_u(:,:,1)=P_0;

aa=-0.00000000000000000000000000000001;

for t=1:TT
    [H,T_star,T,Q_star,Q,Z,d]=state_space(n,k,t,varargin{:});
    gamma          = (chol(Q_star))\(aa-T_star*alpha_u(:,t));
    if normcdf(gamma,0,1)>0.99
        eta_m = 0;
    else
        eta_m          = (normpdf(gamma,0,1))/(1 - normcdf(gamma,0,1));
    end
    nu_m           = 1- eta_m^2+ gamma*eta_m;
    
    alpha_f(:,t)=T*alpha_u(:,t)+ chol(Q_star)'*[eta_m 0]';%+c(:,t);
    P_f(:,:,t)=T*P_u(:,:,t)*T' + chol(Q_star)'*diag([nu_m 0])*chol(Q_star);
    
    Et=data(:,t)-Z*alpha_f(:,t)-Z*chol(Q_star)'*[eta_m 0]'- d;
    P_y=Z*P_f(:,:,t)*Z'+H;
    Kt=P_f(:,:,t)*Z'*eye(size(P_y))/(P_y);
    alpha_u(:,t+1)=alpha_f(:,t)+Kt*Et;
    P_u(:,:,t+1)=P_f(:,:,t) - Kt*Z*P_f(:,:,t);
end

alpha_s(:,TT)=mvnrnd1(alpha_u(:,TT+1),P_u(:,:,TT+1),1);

while alpha_s(1,TT)<=0
    
    alpha_s(:,TT)=mvnrnd1(alpha_u(:,TT+1),P_u(:,:,TT+1),1);
    whx = whx+1;
    
    if whx>10000
        twist = 1;
        disp('Problems with sign of factor loadings at T');
    end
end

whx=0;
for t=TT-1:-1:1
    
    Jt=P_u(:,:,t+1)*T_star' * eye(size(Q_star))/(T_star*P_u(:,:,t+1)*T_star'+ Q_star);
    alpha_st=alpha_u(:,t+1)+Jt*(alpha_s(1:k,t+1)-T_star*alpha_u(:,t+1));%-c(1:k,t)
    P_st=P_u(:,:,t+1)-Jt*T_star*P_u(:,:,t+1);
    alpha_s(:,t)=mvnrnd1(alpha_st,P_st,1);
    
    while alpha_s(1,t)<=0
        alpha_s(:,t)=mvnrnd1(alpha_st,P_st,1);
        whx = whx+1;
        if whx>10000
            twist = 1;
            disp('Problems with sign of factor loadings at t');
        end
    end
    
end

ee=[eye(k) zeros(k,k*(q-1))];

alphat=(ee*alpha_s(:,1:end));

varargout(1) = {twist};